<template>
  <div class="pdf-opener">
    <!-- <button @click="openPdfInNewWindow" class="open-btn">
      在新窗口打开PDF
    </button> -->
  </div>
</template>

<script>
export default {
  name: 'PdfOpener',
  props: {
    // PDF文件的URL地址
    pdfUrl: {
      type: String,
      default: ''
    },
    // 可选：Base64格式的PDF数据
    pdfBase64: {
      type: String,
      default: ''
    }
  },
  methods: {
    /**
     * 在新窗口打开PDF文件
     */
    openPdfInNewWindow() {
      console.log(this.pdfUrl, 'this.pdfUrl')
      if (this.pdfUrl) {
        this.openPdfFromUrl()
      } else if (this.pdfBase64) {
        this.openPdfFromBase64()
      } else {
        console.error('请提供PDF的URL或Base64数据')
      }
    },

    /**
     * 从URL打开PDF
     */
    openPdfFromUrl() {
      // 将Vue响应式代理转换为纯字符串
      const pdfUrlString = String(this.pdfUrl)
      console.log('PDF URL:', pdfUrlString)
      
      // 检查URL是否有效
      try {
        // 对于相对路径，使用当前域名构造完整URL进行验证
        if (pdfUrlString.startsWith('/')) {
          new URL(pdfUrlString, window.location.origin)
        } else {
          new URL(pdfUrlString)
        }
        // 打开新窗口
        window.open(pdfUrlString, '_blank')
      } catch (error) {
        console.error('无效的PDF URL:', error)
      }
    },

    /**
     * 从Base64数据打开PDF
     */
    openPdfFromBase64() {
      try {
        // 创建Blob对象
        const byteCharacters = atob(this.pdfBase64)
        const byteNumbers = new Array(byteCharacters.length)
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i)
        }
        const byteArray = new Uint8Array(byteNumbers)
        const blob = new Blob([byteArray], { type: 'application/pdf' })

        // 创建临时URL
        const url = URL.createObjectURL(blob)

        // 打开新窗口
        window.open(url, '_blank')

        // 释放URL对象
        setTimeout(() => {
          URL.revokeObjectURL(url)
        }, 100)
      } catch (error) {
        console.error('处理Base64 PDF数据失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.open-btn {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.open-btn:hover {
  background-color: #359e75;
}
</style>
